package handlers

import (
	"bookshelf/cache"
	"bookshelf/moders"
	"bookshelf/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func BookLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	cache_key := "cache_key_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user moders.User
	err := moders.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, cache_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, cache_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "错误三次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func BookList(c *gin.Context) {
	var books []moders.Book
	redis_book := "books_list"
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_book).Result()

	if CacheData == "" {
		moders.DB.Find(&books)

		jsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, redis_book, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &books)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": books,
	})
	return
}

func Xq(c *gin.Context) {
	var xq moders.Book
	id := c.Query("id")
	moders.DB.Where("id = ?", id).First(&xq)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": xq,
	})
	return
}
